package com.exam.paper.service;

import com.alibaba.fastjson.JSON;
import com.exam.common.entity.PageRequest;
import com.exam.common.until.IdWorker;
import com.exam.paper.mapper.CategoryMapper;
import com.exam.paper.mapper.PaperMapper;
import com.exam.paper.mapper.ScoreMapper;
import com.exam.paper.mapper.SelectMapper;
import com.exam.paper.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.*;

/**
 * @ClassName : ExamService
 * @Description : 试卷service
 * @Author : WHB
 */

@Service
public class PaperService {

    @Autowired
    PaperMapper paperMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SelectMapper selectMapper;

    @Autowired
    ScoreMapper scoreMapper;

    @Autowired
    IdWorker idWorker;

    /**
     * 分页获取试卷列表
     * @param page
     * @param size
     * @param id
     * @return
     */
    public PageRequest<Paper> queryExamByPage(Integer page, Integer size, Long id) {
        //启动分页
        PageHelper.startPage(page,size);

        Paper exam = new Paper();
        exam.setCreatId(id);

        //获取列表
        List<Paper> list = paperMapper.select(exam);

        //解析分页结果
        PageInfo<Paper> info = new PageInfo<>(list);

        return new PageRequest<Paper>(info.getTotal(),list);
    }

    public PageRequest<Paper> searchList(Integer page, Integer size, Long cid,Long id) {
        //启动分页
        PageHelper.startPage(page,size);

        //搜索条件
        Paper exam = new Paper();
        exam.setCreatId(id);
        exam.setCategoryId(cid);

        //获取列表
        List<Paper> list = paperMapper.select(exam);

        //解析分页结果
        PageInfo<Paper> info = new PageInfo<>(list);

        return new PageRequest<Paper>(info.getTotal(),list);
    }


    /**
     * 新增试卷
     * @param data
     */
    public void addPaper(String data) {
        add(data,null);
    }
    public void add(String data,Long creatId){
        //实例化
        AddPaper addPaper = JSON.parseObject(data, AddPaper.class);
        System.out.println(addPaper.toString()+"1111111111111111111111");
        //创建试卷信息
        Paper paper = new Paper();
        Long pid = idWorker.nextId();
        paper.setId(pid);
        paper.setName(addPaper.getName());
        if (creatId == null){
            paper.setCreatId((long) 666);
        }else {
            paper.setCreatId(creatId);
        }

        Long cid = addPaper.getCid().get(1);
        paper.setCategoryId(cid);

        Category category = new Category();
        category.setId(cid);
        paper.setCategoryName(categoryMapper.selectOne(category).getName());

        paper.setCreatTime(new Date());
        paperMapper.insert(paper);

        //新增题目
        for (Select s:
                addPaper.getSelectList() ) {
            s.setId(idWorker.nextId());
            s.setPaperId(pid);
            selectMapper.insert(s);
        }
    }
    public void adduserPaper(String data, Long creatId) {
        add(data,creatId);
    }

    /**
     * 修改试卷
     * @param data
     */
    public void editPaper(String data) {
        MyPager myPager = JSON.parseObject(data,MyPager.class);

        Paper paper = myPager.getPaper();
        paper.setReviseTime(new Date());

        Long cid = paper.getCategoryId();
        Category category = new Category();
        category.setId(cid);
        paper.setCategoryName(categoryMapper.selectOne(category).getName());
        paperMapper.updateByPrimaryKey(paper);


        List<Select> selectList = myPager.getSelectList();
        //新增题目
        for (int i = 0; i < selectList.size(); i++) {
            if (selectList.get(i).getId() != null){
                //更新
                selectMapper.updateByPrimaryKey(selectList.get(i));
            }else {
                //插入
                selectList.get(i).setId(idWorker.nextId());
                selectList.get(i).setPaperId(paper.getId());
                selectMapper.insert(selectList.get(i));
            }
        }

    }


    /**
     * 根据pid获取试卷信息
     * @param id
     * @return
     */
    public MyPager queryPaperById(Long id) {
        MyPager myPager = new MyPager();

        Paper paper = new Paper();
        paper.setId(id);
        myPager.setPaper(paperMapper.selectOne(paper));

        Select select = new Select();
        select.setPaperId(id);
        myPager.setSelectList(selectMapper.select(select));
        return myPager;
    }

    public EvaluationResult evaluation(String data) {
        Evaluation evaluation = JSON.parseObject(data,Evaluation.class);
        System.out.println(evaluation);

        Long pId = evaluation.getPId();

        List answerList= evaluation.getAnswerList();

        //根据Pid查找试卷
        MyPager myPager = queryPaperById(pId);

        //选择题列表
        List<Select> selectList = myPager.getSelectList();

        //判断对错列表
        List<IsRight> isRightList = new ArrayList<>();

        //正确题数
        int rightNum = 0;



        //返回列表构建
        for (int i = 0; i < selectList.size() ; i++) {
            IsRight isRight = new IsRight();

            //对
            if (selectList.get(i).getAnswer() == Integer.valueOf(answerList.get(i).toString())){
                    isRight.setRight(true);
                    isRight.setOption(Integer.valueOf(answerList.get(i).toString()));
                    isRightList.add(i,isRight);
                    rightNum++;
            }else {//错
                isRight.setRight(false);
                isRight.setOption(Integer.valueOf(answerList.get(i).toString()));
                isRightList.add(i,isRight);
            }
        }

        EvaluationResult evaluationResult = new EvaluationResult();
        evaluationResult.setIsRightList(isRightList);
        evaluationResult.setSelectList(selectList);
        evaluationResult.setPaper(myPager.getPaper());
        evaluationResult.setRightNum(rightNum);

        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String rightPercentage = numberFormat.format((float) rightNum / (float) selectList.size() * 100);//所占百分比
        evaluationResult.setRightPercentage(rightPercentage);


        //持久化保存
        if (evaluation.getTestId() != null){
            Score score = new Score();
            score.setTestId(evaluation.getTestId());
            score.setUserId(evaluation.getUserId());
            score.setScore(rightPercentage);
            scoreMapper.insert(score);
        }

        return  evaluationResult;
    }


    public List<Paper> queryPageList(Long id) {
        Paper paper = new Paper();
        paper.setCreatId(id);
        List<Paper> paperList = paperMapper.select(paper);
        return paperList;
    }

    public List<Paper> queryPageListByCategoryId(Long cid) {
        Paper paper = new Paper();
        paper.setCategoryId(cid);
        paper.setCreatId((long) 666);
        List<Paper> paperList = paperMapper.select(paper);
        return paperList;
    }

    public int getScore(Integer testId, Long userId) {
        Score score = new Score();
        score.setUserId(userId);
        score.setTestId(testId);
        return scoreMapper.selectCount(score);
    }
}
